<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-white shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between h-16">
          <div class="flex items-center">
            <router-link to="/" class="text-xl font-bold text-gray-900">
              {{ $t('app.title') }}
            </router-link>
          </div>

          <div class="flex items-center space-x-4">
            <!-- 语言切换 -->
            <LanguageSwitch />

            <template v-if="authStore.isAuthenticated">
              <router-link
                to="/post/create"
                class="bg-primary-600 hover:bg-primary-700 text-white px-4 py-2 rounded-md text-sm font-medium"
              >
                {{ $t('post.create') }}
              </router-link>
              <router-link
                to="/dashboard"
                class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
              >
                {{ $t('nav.dashboard') }}
              </router-link>
              <button
                @click="handleLogout"
                class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
              >
                {{ $t('auth.logout') }}
              </button>
            </template>
            <template v-else>
              <router-link
                to="/login"
                class="text-gray-700 hover:text-gray-900 px-3 py-2 rounded-md text-sm font-medium"
              >
                {{ $t('auth.login') }}
              </router-link>
              <router-link
                to="/register"
                class="bg-primary-600 hover:bg-primary-700 text-white px-4 py-2 rounded-md text-sm font-medium"
              >
                {{ $t('auth.register') }}
              </router-link>
            </template>
          </div>
        </div>
      </div>
    </nav>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 页面标题和视图切换 -->
      <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-8">
        <div>
          <h1 class="text-3xl font-bold text-gray-900">{{ $t('nav.posts') }}</h1>
          <p class="mt-2 text-gray-600">{{ $t('app.subtitle') }}</p>
        </div>

        <div class="mt-4 sm:mt-0 flex items-center space-x-4">
          <!-- 移除了地图视图切换按钮 -->
        </div>
      </div>

      <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
        <!-- 筛选器侧边栏 -->
        <div class="lg:col-span-1">
          <div class="bg-white rounded-lg shadow p-6 sticky top-8">
            <h3 class="text-lg font-medium text-gray-900 mb-4">{{ $t('common.filterConditions') }}</h3>

            <!-- 关键词搜索 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                {{ $t('common.keywordSearch') }}
              </label>
              <input
                v-model="filters.keyword"
                type="text"
                :placeholder="$t('search.placeholder')"
                class="input-field"
                @input="debouncedSearch"
              />
            </div>

            <!-- 宠物品种 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                {{ $t('post.fields.petSpecies') }}
              </label>
              <select v-model="filters.species" class="input-field" @change="handleFilterChange">
                <option value="">{{ $t('common.all') }}{{ $t('post.fields.petSpecies') }}</option>
                <option v-for="species in petSpeciesOptions" :key="species.value" :value="species.value">
                  {{ species.label }}
                </option>
              </select>
            </div>

            <!-- 毛色 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                {{ $t('post.fields.petColor') }}
              </label>
              <input
                v-model="filters.color"
                type="text"
                class="input-field"
                :placeholder="$t('post.placeholders.enterColorFilter')"
                @input="debouncedSearch"
              />
            </div>

            <!-- 性别 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                {{ $t('post.fields.petGender') }}
              </label>
              <select v-model="filters.gender" class="input-field" @change="handleFilterChange">
                <option value="">{{ $t('common.all') }}{{ $t('post.fields.petGender') }}</option>
                <option v-for="gender in petGenderOptions" :key="gender.value" :value="gender.value">
                  {{ gender.label }}
                </option>
              </select>
            </div>

            <!-- 地区 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                {{ $t('post.fields.location') }}
              </label>
              <select v-model="filters.location" class="input-field" @change="handleFilterChange">
                <option value="">{{ $t('common.all') }}地區</option>
                <option v-for="district in hkDistrictOptions" :key="district.value" :value="district.value">
                  {{ district.label }}
                </option>
              </select>
            </div>

            <!-- 时间范围 -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                {{ $t('post.fields.lostDate') }}
              </label>
              <div class="space-y-2">
                <input
                  v-model="filters.dateFrom"
                  type="date"
                  class="input-field"
                  @change="handleFilterChange"
                />
                <input
                  v-model="filters.dateTo"
                  type="date"
                  class="input-field"
                  @change="handleFilterChange"
                />
              </div>
            </div>

            <!-- 清除筛选 -->
            <button
              @click="clearFilters"
              class="w-full btn-secondary"
            >
              {{ $t('common.clearFilters') }}
            </button>
          </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="lg:col-span-3">
          <!-- 列表视图 -->
          <div>
            <!-- 加载状态 -->
            <div v-if="loading" class="flex justify-center py-12">
              <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
            </div>

            <!-- 帖子列表 -->
            <div v-else-if="posts.length > 0" class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div
                v-for="post in posts"
                :key="post.id"
                @click="goToPostDetail(post.id)"
                class="bg-white rounded-lg shadow hover:shadow-md transition-shadow cursor-pointer"
              >
                <div class="p-6">
                  <!-- 宠物照片 -->
                  <div class="mb-4">
                    <div class="w-full h-48 bg-gray-100 rounded-lg flex items-center justify-center overflow-hidden">
                      <img
                        v-if="post.pet?.photo_url"
                        :src="getFullImageUrl(post.pet.photo_url)"
                        :alt="post.pet.name"
                        class="max-w-full max-h-full object-contain rounded-lg"
                      />
                      <svg
                        v-else
                        class="w-12 h-12 text-gray-400"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                    </div>
                  </div>

                  <!-- 帖子信息 -->
                  <div class="space-y-2">
                    <div class="flex items-center justify-between">
                      <h3 class="text-lg font-semibold text-gray-900">
                        {{ post.pet?.name || $t('common.unknown') }}
                      </h3>
                      <span
                        :class="[
                          'px-2 py-1 text-xs font-medium rounded-full',
                          post.post_status === 'searching'
                            ? 'bg-yellow-100 text-yellow-800'
                            : post.post_status === 'found'
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-800'
                        ]"
                      >
                        {{ $t(POST_STATUS_LABELS[post.post_status]) }}
                      </span>
                    </div>

                    <div class="flex items-center text-sm text-gray-600 space-x-4">
                      <span>{{ post.pet?.species }}</span>
                      <span>{{ post.pet?.color }}</span>
                      <span>{{ getGenderLabel(post.pet?.gender) }}</span>
                    </div>

                    <div class="flex items-center text-sm text-gray-500">
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                      </svg>
                      {{ post.last_seen_location }}
                    </div>

                    <div class="flex items-center text-sm text-gray-500">
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      {{ formatDate(post.last_seen_time) }}
                    </div>

                    <div class="flex items-center text-sm text-gray-500">
                      <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                      </svg>
                      {{ post.owner?.username }}
                    </div>

                    <!-- 操作按钮 -->
                    <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-200">
                      <button
                        @click.stop="goToPostDetail(post.id)"
                        class="text-primary-600 hover:text-primary-700 text-sm font-medium"
                      >
                        {{ $t('common.viewDetails') }}
                      </button>
                      <button
                        @click.stop="openShareModal(post)"
                        class="text-gray-600 hover:text-gray-700 text-sm font-medium"
                      >
                        {{ $t('common.share') }}
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="text-center py-12">
              <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 12h6m-6-4h6m2 5.291A7.962 7.962 0 0112 15c-2.34 0-4.5-.9-6.1-2.3" />
              </svg>
              <h3 class="mt-2 text-sm font-medium text-gray-900">{{ $t('common.noPetInfo') }}</h3>
              <p class="mt-1 text-sm text-gray-500">
                {{ hasFilters ? $t('common.adjustFilters') : $t('common.noPostsYet') }}
              </p>
            </div>

            <!-- 分页 -->
            <div v-if="pagination.totalPages > 1" class="mt-8">
              <Pagination
                :current-page="pagination.page"
                :total-pages="pagination.totalPages"
                :total="pagination.total"
                @page-change="handlePageChange"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分享模态框 -->
    <ShareModal
      v-if="showShareModal && selectedPost"
      :post="selectedPost"
      @close="closeShareModal"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { postService } from '@/services/posts'
// 移除了PostsMap组件导入
import Pagination from '@/components/Pagination.vue'
import ShareModal from '@/components/ShareModal.vue'
import LanguageSwitch from '@/components/LanguageSwitch.vue'
import { debounce, formatDate, getFullImageUrl } from '@/utils/helpers'
import type { Post, SearchFilters, PaginationParams } from '@/types'
import { PAGINATION, POST_STATUS_LABELS } from '@/constants'
import { usePetSpeciesOptions, usePetGenderOptions, useHKDistrictOptions } from '@/utils/i18n-options'

const router = useRouter()
const authStore = useAuthStore()

// 状态
// 移除了viewMode，只保留列表视图
const loading = ref(false)
const posts = ref<Post[]>([])
const pagination = ref({
  page: 1,
  limit: PAGINATION.DEFAULT_LIMIT,
  total: 0,
  totalPages: 0,
})

// 分享相关状态
const showShareModal = ref(false)
const selectedPost = ref<Post | null>(null)

// 国际化选项
const petSpeciesOptions = computed(() => usePetSpeciesOptions())
const petGenderOptions = computed(() => usePetGenderOptions())
const hkDistrictOptions = computed(() => useHKDistrictOptions())

// 筛选条件
const filters = ref<SearchFilters>({
  species: '',
  color: '',
  gender: '',
  location: '',
  dateFrom: '',
  dateTo: '',
  keyword: '',
})

// 计算属性
const hasFilters = computed(() => {
  return Object.values(filters.value).some(value => value !== '')
})

// 工具函数
const getGenderLabel = (gender?: string) => {
  const genderOption = petGenderOptions.value.find(g => g.value === gender)
  return genderOption?.label || gender || ''
}

// 方法
const loadPosts = async () => {
  try {
    loading.value = true

    const params: PaginationParams = {
      page: pagination.value.page,
      limit: pagination.value.limit,
    }

    const response = await postService.getList(filters.value, params)

    if (response.success && response.data) {
      // 服务器返回的格式是 { success, message, data: [...], pagination: {...} }
      // 而不是 { success, message, data: { items: [...], pagination: {...} } }
      posts.value = response.data as Post[]
      // 从响应中获取分页信息
      if ('pagination' in response) {
        pagination.value = {
          page: (response as any).pagination.currentPage,
          limit: (response as any).pagination.itemsPerPage,
          total: (response as any).pagination.totalItems,
          totalPages: (response as any).pagination.totalPages,
        }
      }
    }
  } catch (error) {
    console.error('加载帖子失败:', error)
  } finally {
    loading.value = false
  }
}

const handleFilterChange = () => {
  pagination.value.page = 1
  loadPosts()
}

const debouncedSearch = debounce(() => {
  handleFilterChange()
}, 500)

const clearFilters = () => {
  filters.value = {
    species: '',
    color: '',
    gender: '',
    location: '',
    dateFrom: '',
    dateTo: '',
    keyword: '',
  }
  handleFilterChange()
}

const handlePageChange = (page: number) => {
  pagination.value.page = page
  loadPosts()
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const goToPostDetail = (postId: number) => {
  router.push(`/posts/${postId}`)
}

const handleLogout = async () => {
  await authStore.logout()
  router.push('/')
}

const openShareModal = (post: Post) => {
  selectedPost.value = post
  showShareModal.value = true
}

const closeShareModal = () => {
  showShareModal.value = false
  selectedPost.value = null
}

// 移除了视图模式监听

onMounted(() => {
  loadPosts()
})
</script>
